/** @jsxImportSource @emotion/react */
//import { jsx } from "@emotion/react";
import * as React from "react";
//import { usePaginateQueryTask } from "./db";
import {
    List,
    Text, Stack, StackItem, StackTitle,
    useTheme,
     useMMenuBarOcup, VerticalMenu, DdMenuItem
} from "customize-easy-ui-component";
//import { SearchBox } from "../SearchBox";
//import debug from "debug";
//import algoliasearch from "algoliasearch";
//import config from "./firebase-config";
//import { useSession } from "../auth";
//import find from "lodash.find";
//import { useDeleteRequestFollow, usePaginateQueryUser,  } from "./db";
//import { StackItem } from "react-gesture-stack";
//import { useLocation } from "wouter";
//import { BoundReports } from "./report/BoundReports";
import { SearchTitle } from "../comp/base";
import {PreloadedQuery, usePaginationFragment, usePreloadedQuery, useRefetchableFragment} from "react-relay/hooks";
import {DetailReports$key} from "./__generated__/DetailReports.graphql";
import {SearchBox} from "../comp/SearchBox";
import {useContext} from "react";
import RoutingContext from "../routing/RoutingContext";
import {BoundReports, ReportListItem} from "./report/BoundReports";
import {css} from "@emotion/react";
// import {Stack, StackItem, StackTitle} from "../../UiDebugSave/sample/Stack";

const graphql = require("babel-plugin-relay/macro");

/*export const detailReports2Query= graphql`
    fragment DetailReports on Query
    @refetchable(queryName: "DetailReportsQuery") {
        node(id: $id)
        {
            id, __typename,
            ... on Detail {
                ident,task{id,date,status,liabler{id,person{id,name}} }
                isp{ id,no,ispDate,
                    dev{id,cod}
                    report{id,stm{id,sta,authr{id,person{id,name}}
                        master{id,person{id,name}}
                    } },
                    reps{
                        edges {
                            node{ id,modeltype,modelversion,type,stm{
                                id,sta,cur{id,time,user{id,person{id,name}}}
                            }
                            }
                        }
                    }
                }
            },
        }
    }
`;*/

/*
node(id: $id) {
            id,
            ... on Detail {
                ident,task{id,date,status,liabler{id,person{id,name}} }
                isp{ id,no,ispDate,
                    dev{id,cod}
                    report{id,stm{id,sta,authr{id,person{id,name}}
                        master{id,person{id,name}}
                    } }
                }
            },
            __typename
        }
* */

/*
export const DetailReportsQuery= graphql`
    query DetailReportsQuery($id: ID!) {
        node(id: $id)
        {
            id, __typename,
            ... on Detail {
                ident,task{id,date,status,liabler{id,person{id,name}} }
                isp{ id,no,ispDate,
                    dev{id,cod}
                    report{id,stm{id,sta,authr{id,person{id,name}}
                        master{id,person{id,name}}
                    } },
                    reps{
                        edges {
                            node{ id,modeltype,modelversion,type,stm{
                                id,sta,cur{id,time,user{id,person{id,name}}}
                            }
                            }
                        }
                    }
                }
            },
        }

    }
`;
*/

//两个页面都要使用，独立出来定义
export const DetailReportsQuery= graphql`
    fragment DetailReports on Query
    @refetchable(queryName: "detailReportsQuery") {
        node(id: $id)
        {
            id, __typename,
            ... on Detail {
                ident,task{id,date,status,liabler{id,person{id,name}} }
                isp{ id,no,ispDate,
                    dev{id,cod}
                    report{id,stm{id,sta,authr{id,person{id,name}}
                        master{id,person{id,name}}
                    } },
                    reps{
                        edges {
                            node{ id,modeltype,modelversion,type,stm{
                                id,sta,cur{id,time,user{id,person{id,name}}}
                            }
                            }
                        }
                    }
                }
            },
            ... on Isp {
                 bus{id,ident,task{id,date,status,liabler{id,person{id,name}} }}
                 no,ispDate,
                    dev{id,cod}
                    report{id,stm{id,sta,authr{id,person{id,name}}
                        master{id,person{id,name}}
                    }, isp{id,no}},
                    reps{
                        edges {
                            node{ id,modeltype,modelversion,type,stm{
                                id,sta,cur{id,time,user{id,person{id,name}}}
                            }
                            }
                        }
                    }
            },
        }
    }
`;

interface DetailReportsProps {
    routeData: any;
    isps: DetailReports$key;
    //myQuery: PreloadedQuery<typeof DetailReportsQuery>;   直接定义查询对象版本
}

//该组件也被report模块引用了；
export const DetailReports: React.FunctionComponent<DetailReportsProps> = props => {
    const [data, refetch] = useRefetchableFragment(
        DetailReportsQuery,
        props.isps,
    );

/*    const data = usePreloadedQuery<typeof DetailReportsQuery>(
        DetailReportsQuery,
        props.myQuery,
    );*/

    console.log("来OneTaskWraper看当前的data=",data );
  const theme = useTheme();
  let filtercomp={filter: { id:1 },
    offset:0,
    limit:5,
    orderBy: "id",
    asc: false
  };
    const { node:isp }= data;
    if(!isp)    throw new Error("检验Isp不存在:"+props.routeData.url);
    const { report: mainrep }= isp!;       //提取主报告
    const reports = isp?.reps?.edges?.map((edge) => edge?.node);
  //搜索user的输入:
  const [query, setQuery] = React.useState("");

  //状态管理　relation＝当前显示的或者按钮点击事件产生,关注的user是谁。 null as any告警去除
  const [relation, setRelation] = React.useState(null as any);


  const [, setFilter] = React.useState({where:
        {cod:query },
     });

  const noUsers = !query && (reports?.length === 0);
  //界面轮播 setIndex切换显示界面；   //index不是组件外部那一个同名index；
  const [index, setIndex] = React.useState(0);
    const {history } = useContext(RoutingContext);

  function showRelation(item: any) {
    console.log("点击showRelation？item=", item);
    setRelation(item);
    setIndex(1);
  }

  React.useEffect(() => {
    //console.log("伪善setQueryResul02=" ,query,usersFind);
    let filtercomp={where:
        {cod:query },
      offset:0,
      first:5,
      orderBy: "useDt",
      asc: false
    };
    setFilter(filtercomp);
  }, [query]);
  //这两个useEffect的前后顺序不能颠倒，顺序非常重要，后面的依赖于前面的useEffect更新结果。
  //操作UI副作用；要进一步做修正性处理。
    const {barHeight } = useMMenuBarOcup(history.routeData?.isExact);
    const href = `/task/${isp?.bus?.task?.id}`;
  //上面这个副作用必须 加usersFind，否则无法继续处理后端数据带来的必要的UI反馈变化。
  //控件<Stack 是堆叠式的，像导航条；适用同一个模板显示只需上级给下级参数调整的场景。根据上一叠页面选择触发状态relation给下一叠参数来控制下一级显示；更多嵌套很困难。
  return (
    <Stack  navStyle={css({ position: 'sticky',  top: 0,})}
            style={{
                overflow: 'unset'
            }}
      index={index}
      navHeight={40}
      onIndexChange={i => setIndex(i)}
      items={[
        {
          title: (
              <StackTitle
                  contentAfter={
                      <VerticalMenu>
                          <DdMenuItem label="刷新吧6"
                                      onClick={(e) => {
                                          //  refetch({}, { fetchPolicy: "network-only"});
                                      }}/>
                          <DdMenuItem label="所属任务"
                                      onClick={(e) => {
                                          history.push(href);
                                      }}/>
                      </VerticalMenu>
                  }
                  title={"该次检验的报告列表"}
              />
          ),
          content: (
            <StackItem  css={{
                        marginBottom: `${barHeight}`,
                    }}
                   style={{ position: undefined, boxShadow:undefined }}
            >
              <div
                css={{
                  overflowY: "auto",
                  //overflowY: "scroll", 滚动触发，小屏幕很明显的条，滚动条会随浏览器屏幕设备模式变化样式。
                  height: "100%",
                }}
              >
                { noUsers && (
                  <Text
                    muted
                    css={{
                      fontSize: theme.fontSizes[0],
                      display: "block",
                      margin: theme.spaces.lg
                    }}
                  >
                    队列为空
                  </Text>
                )}

                <List>
                    {reports?.map((report) => (
                        <ReportListItem
                            id={report?.id}
                            key={report?.id!}
                            editable
                            report={report as any}
                            parentId={props.routeData.params.ispId}
                            mainrep={mainrep}
                        />
                    ))}
                </List>

              </div>
            </StackItem>
          )
        },

      {
          title: (
              <StackTitle
                  backTitle={"回退"}
                  contentAfter={
                      relation && (
                          <VerticalMenu>
                              <DdMenuItem label="加个检验主或分项报告"
                                          onClick={(e) => {
                                              history.push(`/inspect/${(relation as any).id}/addReport`);
                                          }}/>
                              <DdMenuItem label={`检验号{(relation as any).id || ''}其他功能`}
                                          onClick={(e) => {
                                          }}/>
                          </VerticalMenu>
                      )
                  }
                  title={relation ? `检验${(relation as any).id}含报告` : ""}
              />
          ),
          content: (
              <StackItem>
                  { relation && (
                    <BoundReports key={relation?.isp.id!} id={relation?.isp.id!}
                        isp={relation.isp}
                    />
                  )}
              </StackItem>
          )
      }

      ]}
    />
  );

};





//报错Cannot read property 'map' of null标记出错代码行，竟可能会差错！实际错误点实在下方，报错指示却在上方的代码行，两处都有.map的代码。
//<Stack 组件，实际上是内部状态控制界面的呈现，实际上DOM数据内容并没有同步地变更，只是页面切换着看；适用数据库组织的；PK的，导航堆叠场景实际是源代码组织的。
//幸运的事！！<StackItem>底下内嵌的组件可以做到每一个都是独立自主的。这里<FollowingRecipes key={}/>对每一个按钮进入和后退的，虽然组件同一个，但内部状态数据可各自独立的。
//overflowY:"scroll"若遇到 css={{height: "100%", 和 minHeight: '300px' 不能同时添加的。overflowY:和"100%"一起使用，且要在内层DIV上用。组件中间层可能屏蔽掉。
//多层DIV的height: "100%", 需要在中间层次添加100%传递父辈限制大小，配合内部层的overflowY: "scroll",才能滚动。
//<Stack多层的下沉层叠＋<ListItem，配合<RouterLink，可以触发点击链接同时还能够下沉页面触发；左右两个页面都能刷新，可是小屏幕只能对照右半部分的核心界面。不触发下沉和要触发条目可同时用。
//点击一次触发多重：<RouterLink to={`/inspect/${item.id}`} >    /  <ListItem  onPress={() =>      /   <Button  onPress={e => { ；；
/*
    <Stack
      css={{
        height: `calc(100vh - 0.875rem - 2 * 10px - 63px)`,
        [theme.mediaQueries.md]: {
          height: `calc(100vh - 2 * ${theme.spaces.lg} - 0.875rem - 2 * 10px - 71px)`
        },
        [theme.mediaQueries.xl]: {
          height: `calc(100vh - 2 * ${theme.spaces.xl} - 0.875rem - 2 * 10px - 71px)`
        }
      }}
* */
